/*
 * UartTool.cpp
 *
 *  Created on: Aug 17, 2025
 *      Author: lydia
 */

#include <UartTool.h>
#include "stm32f1xx_hal.h"
#include <cstring>

UartTool::UartTool(UART_HandleTypeDef *_p_uart)
{
	this->p_uart = _p_uart;

}




void UartTool::UART_send_str(char *p)
{
	HAL_UART_Transmit(p_uart, (uint8_t*) p, strlen(p), 500);
	//HAL_Delay(100);

}
void UartTool::UART_send_bytes(uint8_t *p, int my_len)
{
	// 数组中间有零
	HAL_UART_Transmit(p_uart, (uint8_t*) p, my_len, 500);
}


void UartTool::loop_deal_rcv_buffer()
{
	//执行命令
	for (int i = 0; i < RECEIVER_BUFFER_SIZE; i++)
	{
		if (cmd_receive_buffer[i].buffer_status == 21)
		{
			// 21 接收完成
			// 开始解析执行
			if (cmd_receive_buffer[i].value.device_id == MY_DEVICE_ID)
			{
				// 这个消息是我的，处理
				do_command(i, cmd_receive_buffer[i].cmd);


			}

			//已经处理过了，缓存置空
			cmd_receive_buffer[i].buffer_status = 0;

		}

	}
}

void UartTool::dma_callback()
{
	// 0, 待触发；1，已经收到起始符；2 已经收到CMD_request; 3已经收到长度；4 接收完整Value

	if (uart_receive_status ==0 && rx_byte == 0xFF )
	{
		//1,已经接收到起始符
		uart_receive_status = 1;
		HAL_UART_Receive_DMA(p_uart, &rx_byte, 1);
	}
	else if (uart_receive_status == 1)
	{
		//2,收到cmd，进入2

		// 找到空闲队列
		buffer_receive_pos = -1;
		for(int i =0; i < RECEIVER_BUFFER_SIZE; i++)
		{
			if (cmd_receive_buffer[i].buffer_status == 0 )
			{
				//有未被使用的buffer
				buffer_receive_pos = i;
				break;

			}
		}
		if (buffer_receive_pos >=0 )
		{
			// 有空闲队列
			cmd_receive_buffer[buffer_receive_pos].cmd = rx_byte;
			cmd_receive_buffer[buffer_receive_pos].send_time_ms =
			HAL_GetTick();
			// 20 接收数据中
			cmd_receive_buffer[buffer_receive_pos].buffer_status = 20;
			uart_receive_status = 2;
			HAL_UART_Receive_DMA(p_uart, &rx_byte, 1);

		}
		else
		{
			//
			cmd_receive_buffer[buffer_receive_pos].buffer_status = 0;
			uart_receive_status = 0;
			HAL_UART_Receive_DMA(p_uart, &rx_byte, 1);

		}

	}
	else if(uart_receive_status ==2 )
	{
		//收到len, 进入3
		if (rx_byte<= 30)
		{
			//len(value) <= 30 有效
			cmd_receive_buffer[buffer_receive_pos].cmd_len = rx_byte;
			uart_receive_status = 3;
			memset(rx_buffer, 0, sizeof(rx_buffer));
			HAL_UART_Receive_DMA(p_uart, rx_buffer, rx_byte);

		}
		else
		{
			//长度过长，数据无效，丢弃
			cmd_receive_buffer[buffer_receive_pos].buffer_status = 0;
			uart_receive_status = 0;
			HAL_UART_Receive_DMA(p_uart, &rx_byte, 1);
		}
	}
	else if(uart_receive_status ==3 )
	{
		//接收所有value
		// deviceid是否相等
		if (rx_buffer[1] == MY_DEVICE_ID)
		{
			memcpy(&(cmd_receive_buffer[buffer_receive_pos].value),
					rx_buffer,
					cmd_receive_buffer[buffer_receive_pos].cmd_len);
			// 接收完成
			cmd_receive_buffer[buffer_receive_pos].buffer_status = 21;

		}
		else
		{
			//如果deviceid不等，就不是发给我的消息，直接丢弃。
		}

		// 去接收下一条消息
		uart_receive_status = 0;
		HAL_UART_Receive_DMA(p_uart, &rx_byte, 1);
	}
	else
	{
		HAL_UART_Receive_DMA(p_uart, &rx_byte, 1);
	}

}
